<?php
	class Image {

		const POSITION_CENTER       = 'center';
		const POSITION_BOTTOM_RIGHT = 'bottom_right';

		public static function addWatermark($in_file, $out_file, $watermark_file, $position = self::POSITION_CENTER) {
			$image = new Imagick();
			$image->readImage($in_file);

			$watermark = new Imagick();
			$watermark->readImage($watermark_file);

			$iWidth  = $image->getImageWidth();
			$iHeight = $image->getImageHeight();
			$wWidth  = $watermark->getImageWidth();
			$wHeight = $watermark->getImageHeight();

			if ($iHeight < $wHeight || $iWidth < $wWidth) {
				$watermark->scaleImage($iWidth, $iHeight);

				$wWidth  = $watermark->getImageWidth();
				$wHeight = $watermark->getImageHeight();
			}

			switch ($position) {
				case self::POSITION_BOTTOM_RIGHT:
					$x = $iWidth - $wWidth;
					$y = $iHeight - $wHeight;
					break;
				case self::POSITION_CENTER:
					$x = ($iWidth - $wWidth) / 2;
					$y = ($iHeight - $wHeight) / 2;

					break;
				default:
					$x = 0;
					$y = 0;
			}

			$image->compositeImage($watermark, imagick::COMPOSITE_OVER, $x, $y);

			$image->writeImage($out_file);

			unset($image);
			unset($watermark);
		}

		public static function convertImage($in_file, $out_file, $format = 'jpg') {
			$image = new Imagick($in_file);
			$image->setImageFormat($format);
			$image->writeImage($out_file);

			unset($image);
			unlink($in_file);
		}

		public static function resizeImage($in_file, $out_file, $width = null, $height = null) {
			$image = new Imagick();
			$image->readImage($in_file);

			$iWidth  = $image->getImageWidth();
			$iHeight = $image->getImageHeight();

			if (is_null($width) && is_null($height)) return;

			if (is_null($width)) {
				$width = (int)round($iWidth * $height / $iHeight);
			}
			if (is_null($height)) {
				$height = (int)round($iHeight * $width / $iWidth);
			}

			$image->scaleImage($width, $height);
			$image->writeImage($out_file);
		}
	}